package com.nf.xiaomi.dao.impl;

import com.nf.dbutils.SqlExecutor;
import com.nf.dbutils.handlers.BeanListHandler;
import com.nf.dbutils.handlers.ScalarHandler;
import com.nf.xiaomi.dao.CategoryDao;
import com.nf.xiaomi.entity.CategoryEntity;
import com.nf.xiaomi.util.SqlExecutorUtils;

import java.util.List;

public class CategoryDaoImpl implements CategoryDao {
    SqlExecutor executor = SqlExecutorUtils.getExecutor();
    @Override
    public List<CategoryEntity> getAll() {
        String sql="select category_id,category_name from category";
        BeanListHandler<CategoryEntity> handler=new BeanListHandler<>(CategoryEntity.class);
        return executor.query(sql, handler);
    }

    @Override
    public int insert(String name) {
        String sql = "insert into category(category_name) values(?)";
        return executor.update(sql, name);
    }

    @Override
    public int update(Integer id, String name) {
        String sql = "update category set category_name = ? where category_id = ?";
        return executor.update(sql, name,id);
    }

    @Override
    public int delete(Integer id) {
        String sql = "delete from category where category_id = ?";
        return executor.update(sql, id);
    }

    @Override
    public int selectCidByName(String cname) {
        String sql = "select category_id from category where category_name = ?";
        Integer query = (Integer) executor.query(sql, new ScalarHandler<>(), cname);
        if (query == null) {
            return 0;
        }
        return query;
    }

    @Override
    public String selectNameByCid(int id) {
        String sql = "select category_name from category where category_id = ?";
        Object query = executor.query(sql, new ScalarHandler<>(), id);
        return query.toString();
    }
}
